<?php

/**
 * TomatoCMS
 *
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 *
 * @copyright    Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license        http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version     $Id: ShoppingcartController.php 3075 2010-05-26 15:41:59Z quanvo $
 */

class Advertise_AdvertiseController extends Zend_Controller_Action {

	public function mainpageAction(){
		$path_data 		   = 'application/modules/b2b/widgets/data';
		require_once 	   $path_data.'/mainpageXML.php';
		$path_xml_mainpage = $path_data . '/mainpage.xml';
		$mainpageObj = new mainpageXML($path_xml_mainpage);
		$request = $this->getRequest();
		if($request->isPost()){			
			$params = $request->getParams();			
			$action_type  = $params["action_type"];
			$this->view->assign("action_type",$action_type);
			switch($action_type){
				case "links": 
						$name = isset($params['links']['name'])?$params['links']['name']:null;
						$name_en = isset($params['links']['name_en'])?$params['links']['name_en']:null;
						$url  = isset($params['links']['url'])?$params['links']['url']:null;						
						if($name){
							$arrlinks = array();
							foreach($name as $index => $item_name){
								$arrlinks[] = array("name"=> $item_name,"name_en"=>$name_en[$index],"url"=>$url[$index]);
							}
							$mainpageObj->setLinks($arrlinks);
						}
					break;
				case "vips" : 
					
					$file     = isset($_FILES['vips_file']) ? $_FILES['vips_file']:null;
					$img_url  = isset($params['vips']['img_url'])?$params['vips']['img_url']:null;
					$vip_name = isset($params['vips']['vip_name'])?$params['vips']['vip_name']:null;
					$qoute = isset($params['vips']['qoute'])?$params['vips']['qoute']:null;
					$qoute_en = isset($params['vips']['qoute_en'])?$params['vips']['qoute_en']:null;
					
					$vip_positions = isset($params['vips']['vip_positions'])?$params['vips']['vip_positions']:null;					
					$vip_positions_en = isset($params['vips']['vip_positions_en'])?$params['vips']['vip_positions_en']:null;
					if($vip_name){
						$arrVips = array();
						foreach($vip_name as $index => $vip_name_item){	
							$img_url_tmp = $img_url[$index];
							if($file["name"][$index]){// upload file to server	
								$path_upload = 'images/advertise/mainpage/vips';								
								if(!empty($img_url[$index])){
									$file_name = pathinfo($file["name"][$index]);
									
									$file_name = $file_name['filename']. '.'.(empty($file_name['extension']) ? 'png': $file_name['extension']);
								}
								else
									$file_name = $file["name"][$index];
								$path_upload .= '/' . $file_name;	 
								move_uploaded_file($file["tmp_name"][$index],$path_upload);
								$img_url_tmp  = $this->view->APP_STATIC_SERVER .'/'.$path_upload;
							}
							$arrVips[] = array("img_url"=> $img_url_tmp,"vip_name"=>$vip_name[$index],
												"qoute"=>$qoute[$index],"qoute_en"=>$qoute_en[$index],
												'vip_positions'=>$vip_positions[$index],'vip_positions_en'=>$vip_positions_en[$index]);
						}
						$mainpageObj->setVips($arrVips);
					}					
					break;
				case "advs" : 
					$file     = isset($_FILES['advs_file']) ? $_FILES['advs_file']:null;
					$img_url = isset($params['advs']['img_url'])?$params['advs']['img_url']:null;
					$link    = isset($params['advs']['link'])?$params['advs']['link']:null;
					if($img_url){
						$arrAdvs = array();
						foreach($img_url as $index => $img_urlItem){
							$img_url_tmp = $img_url[$index];
							if($file["name"][$index]){// upload file to server	
								$path_upload = 'images/advertise/mainpage/advs';								
								if(!empty($img_url[$index])){
									$file_name = pathinfo($file["name"][$index]);
									$file_name = $file_name['filename']. '.'.(empty($file_name['extension']) ? 'png': $file_name['extension']);
								}else
									$file_name = $file["name"][$index];
								$path_upload .= '/' . $file_name;	 
								move_uploaded_file($file["tmp_name"][$index],$path_upload);
								$img_url_tmp  = $this->view->APP_STATIC_SERVER .'/'.$path_upload;
							}						
							$arrAdvs[] = array("img_url"=> $img_url_tmp,"link"=>$link[$index]);
						}
						$mainpageObj->setAdvs($arrAdvs);
					}					
					break;
				case "slogans" : 
					$qoute = isset($params['slogans']['qoute'])?$params['slogans']['qoute']:null;
					$qoute_en = isset($params['slogans']['qoute_en'])?$params['slogans']['qoute_en']:null;
					if($qoute){
						$arrSlogans = array();
						foreach($qoute as $index => $item){
							$arrSlogans[] = array("qoute"=> $qoute[$index],"qoute_en"=> $qoute_en[$index]);
						}
						$mainpageObj->setSlogans($arrSlogans);
					}					
					break;
				case "professions" : 
					$file     	= isset($_FILES['professions_file']) ? $_FILES['professions_file']:null;
					$name 		= isset($params['professions']['name'])?$params['professions']['name']:null;
					$name_en 	= isset($params['professions']['name_en'])?$params['professions']['name_en']:null;
					$img_url 	= isset($params['professions']['img_url'])?$params['professions']['img_url']:null;
					$enterprise = isset($params['professions']['enterprise'])?$params['professions']['enterprise']:null;
					if($name){
						$arrProfessions = array();
						foreach($name as $index => $item){
							$img_url_tmp = $img_url[$index];
							if($file["name"][$index]){// upload file to server	
								$path_upload = 'images/advertise/mainpage/professions';								
								if(!empty($img_url[$index])){
									$file_name = pathinfo($file["name"][$index]);
									$file_name = $file_name['filename']. '.'.(empty($file_name['extension']) ? 'png': $file_name['extension']);
								}else
									$file_name = $file["name"][$index];
								$path_upload .= '/' . $file_name;	 
								move_uploaded_file($file["tmp_name"][$index],$path_upload);
								$img_url_tmp  = $this->view->APP_STATIC_SERVER .'/'.$path_upload;
							}						
							$arrProfessions[] = array(
								"name"=> $name[$index],
								"name_en"=> $name_en[$index],
								"img_url"=>$img_url_tmp,
								"enterprises"=>explode(',',$enterprise[$index])
							);
						}
						$mainpageObj->setProfessions($arrProfessions);
					}					
					break;
						
					
			}
			$mainpageObj = new mainpageXML($path_xml_mainpage);
		}else
			$this->view->assign("action_type","links");
		$links 		= $mainpageObj->getLinks();
		$vips 		= $mainpageObj->getVips();
		$advs 		= $mainpageObj->getAdvs();
		$slogans 	= $mainpageObj->getSlogans();
		$professions = $mainpageObj->getProfessions();
		$this->view->assign("links",$links);	
		$this->view->assign("vips",$vips);	
		$this->view->assign("advs",$advs);	
		$this->view->assign("slogans",$slogans);	
		$this->view->assign("professions",$professions);			
	}
    public function productAction(){
        $request = $this->getRequest();
        $id = $request->getParam('id',0);
        $this->view->assign('id', $id);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Category model access to data
        **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Advertise model access to data
        **/
        $advertiseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('advertise')->getAdvertiseDao();
        $advertiseDao->setDbConnection($conn);

        /**
        * Get category level 1 for selectbox
        **/
        $categories = $categoryDao->getDirSubCategory(0);
        $this->view->assign('categories', $categories);

        $product_id_chain = null;
        $arrLink = null;
        /**
        * Get old product advertise
        **/
        $products = $advertiseDao->advertise($id);
        foreach($products as $product){
            $product_id_chain .= $product->product_id.',';
        }

        /**
         * Get link advertise
        **/
        $serUrl = $this->view->APP_STATIC_SERVER. "/images/advertise/products";
        $file = $serUrl."/".$id."_link.txt";
        $path = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file);
        if(is_file($path)){
            $content = file_get_contents($path);
            $arrLink = Zend_Json::decode($content);

        }
        $this->view->assign('product_id_chain',substr($product_id_chain,0,-1));
        $this->view->assign('arrLink', $arrLink);

        if($request->isPost()){
            $category = $request->getPost('category');
            $id_chain = $request->getPost('id_chain');
            $links    = $request->getPost('link');

            /**
             * Update image
            **/
            foreach($_FILES['image']['name'] as $key=>$row){
                if($row){
                    $cwd_path = getcwd()."/images/advertise/products/";
                    $name = $category.'_sanpham'.($key+1).'.jpg';
                    $target_path = $cwd_path . basename($name);
                    move_uploaded_file($_FILES['image']['tmp_name'][$key], $target_path);
                }
            }

            /**
             * Update link
            **/
            $strLink = Zend_Json::encode($links);

            $serUrl = $this->view->APP_STATIC_SERVER. "/images/advertise/products";
            $file   = $serUrl."/".$category."_link.txt";
            $path   = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file);
            if(!is_file($path)){
                $ourFileName = $serUrl."/".$category."_link.txt";
                $path = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$ourFileName);
                $ourFileHandle = fopen($path, 'w') or die("can't open file");

                /**
                 * Write to file
                **/
                fwrite($ourFileHandle, $strLink);
            }else{
                $ourFileHandle = fopen($path, 'w') or die("can't open file");
                /**
                 * Write to file
                **/
                fwrite($ourFileHandle, $strLink);
            }
            fclose($ourFileHandle);

            /**
             * Update product advertise
            **/
            if(trim($id_chain)){
                $arrId = explode(',', $id_chain);
                $i = 0;
                foreach($arrId as $p_id){
                    if(is_numeric($p_id)){
                        if($i < 15){
                            $data = array(
                                'product_id'  => $p_id,
                                'category_id' => $category,
                                'advertise'   => 1
                            );
                            $advertiseDao->update($data);
                        }else{
                            break;
                        }
                        $i++;
                    }
                }

                /**
                 * Unadvertise product
                **/
                $advertiseDao->unadvertise($category, $id_chain);
            }
            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'advertise_advertise_product').'/?id='.$category);
        }
    }

    public function enterpriseAction(){
        $request = $this->getRequest();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Advertise model access to data
        **/
        $advertiseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('advertise')->getAdvertiseDao();
        $advertiseDao->setDbConnection($conn);

        /**
        * Get old enterprise advertise
        **/
        $enterprise_id_chain = null;
        $enteprises = $advertiseDao->enAdvertise();
        //print_r($enteprises);die;
        foreach($enteprises as $enteprise){
            $enterprise_id_chain .= $enteprise->enterprise_id.',';
        }
        $this->view->assign('enterprise_id_chain',substr($enterprise_id_chain,0,-1));

        /**
         * Get link advertise
        **/
        $arrLink = null;
        $serUrl = $this->view->APP_STATIC_SERVER. "/images/advertise/enterprise";
        $file = $serUrl."/link.txt";
        $path = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file);
        if(is_file($path)){
            $content = file_get_contents($path);
            $arrLink = Zend_Json::decode($content);
        }
        $this->view->assign('arrLink',$arrLink);

        if($request->isPost()){
            $id_chain = $request->getPost('id_chain');
            $links    = $request->getPost('link');

            /**
             * Update image
            **/
            foreach($_FILES['image']['name'] as $key=>$row){
                if($row){
                    $cwd_path = getcwd()."/images/advertise/enterprise/";
                    $name = 'enterprise_ad'.($key+1).'.jpg';
                    $target_path = $cwd_path . basename($name);
                    move_uploaded_file($_FILES['image']['tmp_name'][$key], $target_path);
                }
            }

            /**
             * Update link
            **/
            $strLink = Zend_Json::encode($links);

            $serUrl = $this->view->APP_STATIC_SERVER. "/images/advertise/enterprise";
            $file   = $serUrl."/link.txt";
            $path   = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$file);
            if(!is_file($path)){
                $ourFileName = $serUrl."/link.txt";
                $path = str_replace($this->view->APP_STATIC_SERVER,getcwd(),$ourFileName);
                $ourFileHandle = fopen($path, 'w') or die("can't open file");

                /**
                 * Write to file
                **/
                fwrite($ourFileHandle, $strLink);
            }else{
                $ourFileHandle = fopen($path, 'w') or die("can't open file");
                /**
                 * Write to file
                **/
                fwrite($ourFileHandle, $strLink);
            }
            fclose($ourFileHandle);

            /**
             * Update enterprise advertise
            **/
            if(trim($id_chain)){
                $arrId = explode(',', $id_chain);
                $i = 0;
                foreach($arrId as $e_id){
                    if(is_numeric($e_id)){
                        if($i < 15){
                            $data = array(
                                'enterprise_id'  => $e_id,
                                'advertise'   => 1
                            );
                            $advertiseDao->enUpdate($data);
                        }else{
                            break;
                        }
                        $i++;
                    }
                }

                /**
                 * Un advertise enterprise
                **/
                $advertiseDao->enUnadvertise($id_chain);
            }
            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'advertise_advertise_enterprise'));
        }
    }
}